package com.example.controller;

import com.example.domain.Delivery;
import com.example.service.IDeliveryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/delivery")
@PreAuthorize("hasAnyAuthority('supplier')")
public class DeliveryController {

    @Autowired
    private IDeliveryService deliveryService;

    @PostMapping("/add")
    public ResponseEntity<String> createDelivery(@RequestBody Delivery delivery) {
        boolean result = deliveryService.createDelivery(delivery);
        if (result) {
            return ResponseEntity.status(HttpStatus.OK).body("配送创建成功");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("创建配送失败");
        }
    }

    @PutMapping("/update")
    public ResponseEntity<String> updateDelivery(@RequestBody Delivery delivery) {
        boolean result = deliveryService.updateDelivery(delivery);
        if (result) {
            return ResponseEntity.status(HttpStatus.OK).body("配送修改成功");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("修改配送失败");
        }
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<String> deleteDelivery(@PathVariable int id) {
        boolean result = deliveryService.deleteDeliveryById(id);
        if (result) {
            return ResponseEntity.status(HttpStatus.OK).body("配送删除成功");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("删除配送失败");
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<Delivery> getDelivery(@PathVariable int id) {
        Delivery delivery = deliveryService.getDeliveryById(id);
        if (delivery != null) {
            return ResponseEntity.status(HttpStatus.OK).body(delivery);
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }
    @GetMapping("/findbyuid/{uid}")
    public ResponseEntity<List<Delivery>> getDeliveriesByUid(@PathVariable int uid) {
        List<Delivery> deliveries = deliveryService.getDeliveriesByUid(uid);
        if (deliveries != null && !deliveries.isEmpty()) {
            return ResponseEntity.status(HttpStatus.OK).body(deliveries);
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }
}